package xyz.lxbq.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import xyz.lxbq.pojo.Emp;
import xyz.lxbq.service.EmpService;
import xyz.lxbq.utils.ResultMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;
/**
 * @author XuHu
 * @version 1.0
 * @date 2020/10/16 10:02
 * 负责项目中的上传
 */
@Controller
public class UploadController {
    /**
     * 文件上传
     */
    @ResponseBody
    @RequestMapping("/photoupload")
    ResultMessage upload(@RequestParam("file") MultipartFile f, HttpSession session, HttpServletRequest request) throws IOException {
//        String filename = f.getOriginalFilename();
//        //截取文件后缀
//        String[] split = filename.split("\\.");
//        //包装文件名防止重名
//        UUID uuid = UUID.randomUUID();
//        String str = uuid.toString();
//        // 去掉"-"符号
//        String temp = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
//        String fName = temp + "." + split[split.length - 1];
//        //超级傻逼的上传功能 待优化
//        String nodepath = request.getSession().getServletContext().getRealPath("");
//        File file = new File(nodepath);
//        String s = file.getParent().toString();
//        String parent = new File(s).getParent();
//        String realPath = parent + "\\src\\main\\webapp\\media\\upload\\"+fName;
//        //实现文件上传
//        f.transferTo(new File(realPath));
//        //获取文件上传的真实的文件服务器路径
//        String realPath1 = parent + "\\target\\OA\\media\\upload\\"+fName;
//        Files.copy(new File(realPath).toPath(), new File(realPath1).toPath());
//        //存储结果
//        ResultMessage message = new ResultMessage(200, fName);
//        //返回结果
//        return message;
        String originalFilename = f.getOriginalFilename();
        String[] split = originalFilename.split("\\.");
        String s = UUID.randomUUID().toString() + "." + split[split.length - 1];
        String realPath = session.getServletContext().getRealPath("/media/upload");
        realPath=realPath+"\\"+s;
        f.transferTo(new File(realPath));

        ResultMessage resultMessage = new ResultMessage(200,s);
        return resultMessage;
    }


}
